package main

import (
	"fmt"
	"os"
	"reflect"
	"runtime"

	"github.com/astaxie/beego"
	"github.com/urfave/cli"

	_ "siasweb/routers"
	"strings"
)

var app = NewApp("", "the command line interface")

func init() {
	// Initialize the CLI app and start server
	app.Action = servers
	app.HideVersion = true // we have a command to print the version
	app.Commands = []cli.Command{
		{
			Action: version,
			Name:   "version",
			Usage:  "print version numbers",
			Description: `
The output of this command is supposed to be machine-readable.
`,
		},
	}

	app.Flags = []cli.Flag{}

	app.Before = func(ctx *cli.Context) error {
		runtime.GOMAXPROCS(runtime.NumCPU())
		return nil
	}

	app.After = func(ctx *cli.Context) error {

		//server.Stop() //grpc服务
		return nil
	}
}

func main() {

	beego.Run()
	//fmt.Println("this ok!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
	if err := app.Run(os.Args); err != nil {
		fmt.Println("cli run")
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

// NewApp creates an app with sane defaults.
func NewApp(gitCommit, usage string) *cli.App {
	app := cli.NewApp()
	app.Name = "StockAnalysisServer" //filepath.Base(os.Args[0])
	app.Author = "zwh"
	//app.Authors = nil
	app.Email = "zwhbin@hotmail.com"
	app.Version = "0.1.0"
	if gitCommit != "" {
		app.Version += "-" + gitCommit[:8]
	}
	app.Usage = usage
	return app
}

func servers(ctx *cli.Context) error {

	// scanner := bufio.NewScanner(os.Stdin)
	// for scanner.Scan() {
	// 	line := scanner.Text()

	// 	fmt.Println(line, "is not a cmd!")
	// }
	// if err := scanner.Err(); err != nil {
	// 	fmt.Fprintln(os.Stderr, "reading standard input:", err)
	// }

	return nil
}

func version(c *cli.Context) error {
	fmt.Println(strings.Title(app.Name))
	fmt.Println("Version:", app.Version)
	fmt.Println("Go Version:", runtime.Version())
	fmt.Println("OS:", runtime.GOOS)
	fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
	fmt.Printf("GOROOT=%s\n", runtime.GOROOT())

	return nil
}

func HandleCmdAction(action interface{}, ps string) (err error) {
	if reflect.TypeOf(action).Kind() != reflect.Func {
		return fmt.Errorf("ERROR invalid Action type.")
	}
	vals := reflect.ValueOf(action).Call([]reflect.Value{reflect.ValueOf(ps)})
	if len(vals) == 0 {
		return nil
	}
	if retErr, ok := vals[0].Interface().(error); vals[0].IsValid() && ok {
		return retErr
	}
	return err
}
